package com.bjsdzk.common.utils;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：cc.
 * @Date：Created in 13:54 2019-12-27
 * @Description：
 * @Version:1.0
 */
public class GaodeUtil {
    private final static Logger logger = LoggerFactory.getLogger(GaodeUtil.class);

    final static String CREATE_API = "http://restapi.amap.com/v3/geocode/geo?";
    final static String KEY = "507de00c91710cf81bb0e7a2cfc26263";

    public static void main(String[] args) {
        Map<String, Double> test = getPoint("北京市朝阳区团结湖");
        for (Map.Entry<String, Double> entry : test.entrySet()) {
            System.out.println(entry.getKey() + "---" + entry.getValue());
        }
    }
    public static Map<String, Double> getPoint(String address) {
        String url = CREATE_API + "key=" + KEY + "&s=rsv3&address=" + address;

        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = HttpClients.createDefault();

        Map<String, Double> resMap = new HashMap<>();
        double lat = 0;
        double lng = 0;
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String strResult = EntityUtils.toString(httpResponse.getEntity());
                if (!StringUtils.isEmpty(strResult)) {
                    JSONObject json = JSON.parseObject(strResult);
                    if (json != null && "1".equals(json.getString("status"))) {
                        JSONObject pointJson = json.getJSONArray("geocodes").getJSONObject(0);
                        String location = pointJson.getString("location");
                        String[] split = location.split(",");
                        lat = Double.parseDouble(split[1]);
                        lng = Double.parseDouble(split[0]);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resMap.put("lat", lat);
        resMap.put("lng", lng);

        return resMap;
    }
}
